package com.fwj.user.web.user;

import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.annotation.LoginUser;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.user.api.user.UserService;
import com.fwj.user.entity.user.UserBaseInfo;
import com.fwj.user.model.user.UserDetailsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: fwj
 * @Data: 2021/11/26 11:10
 * @Version 1.0
     * @Description:    User服务 User Controller层接口
 */

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * @Description 用户修改接口
     * @Param: jsonObject
     * @Author fwj
     * @return com.fwj.core.util.model.ResponseDTO
     * @Createtime 2021/12/23
     */
    @PostMapping("/saveUser")
    public JSONObject saveUser(@RequestBody JSONObject jsonObject, @LoginUser UserBaseInfo userBaseInfo){
        try {
            //解析转化数据并转化
            UserDetailsInfo userDetailsInfo = buildUserDetails(jsonObject,userBaseInfo);
            return userService.saveUser(userDetailsInfo);
        } catch (Exception e){
            return new ResponseDTO().fail();
        }
    }

    /**
     * @Description 用户冻结接口
     * @Param: jsonObject
     * @Author fwj
     * @return com.fwj.core.util.model.ResponseDTO
     * @Createtime 2021/12/23
     */
    @PostMapping("/frozenUser")
    public JSONObject frozenUser(HttpServletRequest request,@RequestBody JSONObject jsonObject, @LoginUser UserBaseInfo userBaseInfo){
        return userService.frozenUser(jsonObject,userBaseInfo);
    }

    @PostMapping("/getUserInfo")
    public JSONObject getUserInfo(@RequestBody JSONObject jsonObject, @LoginUser UserBaseInfo userBaseInfo){
        try {
            //解析转化数据并转化
            UserDetailsInfo userDetailsInfo = buildUserDetails(jsonObject,userBaseInfo);
            return userService.getUserInfo(userDetailsInfo);
        } catch (Exception e){
            return new ResponseDTO().fail();
        }
    }

    private UserDetailsInfo buildUserDetails(JSONObject jsonObject, UserBaseInfo userBaseInfo) {
        UserDetailsInfo userDetailsInfo = JSONObject.parseObject(jsonObject.toJSONString(),UserDetailsInfo.class);
        UserBaseInfo paramUser = userDetailsInfo.getUserBaseInfo();
        if (CommonUtils.isEmpty(paramUser)){ paramUser = new UserBaseInfo(); }
        paramUser.setId(userBaseInfo.getId());
        paramUser.setNumber(userBaseInfo.getNumber());
        userDetailsInfo.setUserBaseInfo(paramUser);
        return userDetailsInfo;
    }
}
